package com.hjy.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.util.Scanner;

/**
 * @version 1.0
 * @Author HJY_Maker
 * @Date 2024/5/21 星期二 15:33
 */
public class FanoutProducer {


    private static final String EXCHANGE_NAME = "fanout-exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        //创建链接和通道
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //创建交换机 声明fanout类型的交换机
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String message = scanner.nextLine();
                //将消息发送到指定的交换机(fanout交换机),不指定而路由键(空字符串)
                channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "'");
            }
        }
    }
}
